// areas is a variable containing all the areas available in the database
//var areas_preference = new Array ();


// area object
function area (area_id, area_name) {
	this.area_id = area_id;
	this.area_name = area_name;
}

// area sorting function
function sort_area(a,b) {
	return a.area_name > b.area_name;
}

// check whether an area is alr in the area preference.
// return true if alr existed, and false otherwise.
function exist_area(area) {
	var flag = false;
	for (var i=0; i < area_preference.length; ++i) {
		if (area_preference[i].area_id == area.area_id) {
			flag = true;
			break;
		}
	}
	return flag;
}

// add new area
function add_area() {
	var chosen_area = document.getElementById("choose_area");
	var new_area = new area (areas[chosen_area.value-1].area_id,
									 areas[chosen_area.value-1].area_name);
	
	if (exist_area(new_area) == false) {
		area_preference.push(new_area);
		area_preference.sort(sort_area);
		display_area();
	}
	
	update_area();
}

// display the area container
function display_area() {
	var area_container = document.getElementById("area_container");
	
	while (area_container.hasChildNodes()) {
		area_container.removeChild(area_container.lastChild);
	}
	
	for (var i=0; i < area_preference.length; ++i) {
		var newdiv = document.createElement('div');
		newdiv.setAttribute('id','area_' + area_preference[i].area_id);
		
		var cancel = document.createElement('a');
		cancel.setAttribute('href','Javascript:void(0);');
		cancel.setAttribute('id','cancel_'+i);
		cancel.setAttribute('onclick','remove_area(' + area_preference[i].area_id + ')');
		cancel.innerHTML = "Remove";
		newdiv.appendChild(cancel);
		
		var text = document.createElement('span');
		text.setAttribute('class', 'normal-text');
		text.innerHTML = "&nbsp-- " + area_preference[i].area_name;
		newdiv.appendChild(text);
		
		area_container.appendChild(newdiv);
	}
}

// remove the corresponding category when a cancel is click
function remove_area(no) {
	var area_container = document.getElementById("area_container");
	var area = document.getElementById('area_' + no);
	
	for (var i=0; i < area_preference.length; ++i) {
		if (area_preference[i].area_id == no) {
			area_preference.splice(i,1);
			break;
		}
	}
	area_container.removeChild(area);
	update_area();
}

// Update the area list input form to send to the sever;
function update_area(){
	var area_list = document.getElementById("area_list");

	area_list.value = area_array_to_string(area_preference);
}

// Convert an array of area to string (only keep the area_id)
function area_array_to_string(a){
	var str = "[" ;
	
	for (var i=0; i < a.length-1; ++i) {
		str += '{"area_id":"' + a[i].area_id + '"},' ;
	}
	if (a.length > 0) {
		str += '{"area_id":"' + a[a.length-1].area_id + '"}' ;
	}
	str += "]";
	
	return str;
}

$(function() {
	display_area();
	update_area();
});